package com.gmj.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gmj.config.MyConfig;
import com.gmj.entity.Student;
import com.gmj.entity.StudentWorkhome;
import com.gmj.entity.Teacher;
import com.gmj.service.IStudentService;
import com.gmj.service.IStudentWorkhomeService;
import com.gmj.utils.FileUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gmj
 * @since 2022-01-29
 */
@RestController
@RequestMapping("/studentWorkhome")
public class StudentWorkhomeController {
    @Autowired
    private IStudentWorkhomeService sws;
    @Autowired
    private IStudentService ss;
    @Value("${attachPath}")
    private String path;
    @GetMapping("/selectAll")
    public List<StudentWorkhome> selectAll(){
        return sws.list();
    }

    @GetMapping("/selectByWorkhome/{wid}")
    public List<StudentWorkhome> selectByWorkhome(@PathVariable("wid") int wid){
        QueryWrapper<StudentWorkhome> wrapper=new QueryWrapper<>();
        wrapper.eq("wid",wid);
        List<StudentWorkhome> list = sws.list(wrapper);
        List<Student> stuList = ss.list();
        list=list.stream().peek((swh)->{
            Student student = stuList.stream().filter((stu) -> {
                return stu.getId() == swh.getSid();
            }).collect(Collectors.toList()).get(0);
            swh.setStudent(student);
        }).collect(Collectors.toList());
        return list;
    }
    @PostMapping("/uploadAttach")
    public String uploadAttach(MultipartFile attach) throws IOException {
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        String oldName=attach.getOriginalFilename();//获取到上传的文件的原始文件名
        String newName = UUID.randomUUID().toString()+oldName;
        attach.transferTo(new File(path,newName));
        return newName;
    }
    @PostMapping("/add")
    public void add(@RequestBody StudentWorkhome swh, HttpSession session) {
        Student student = (Student)session.getAttribute("user");
        swh.setSid(student.getId());
        swh.setUpDate(LocalDateTime.now());
        sws.save(swh);
    }

    @PostMapping("/updateHomework")
    public void updateHomework(@RequestBody StudentWorkhome swh,HttpSession session){
        Teacher teacher = (Teacher) session.getAttribute("user");
        swh.setTid(teacher.getId());
        sws.updateById(swh);
    }
    @GetMapping("/batchDownload/{wid}")
    public void batchDownload(@PathVariable("wid")int wid,HttpServletResponse response) throws Exception {
        QueryWrapper<StudentWorkhome> wrapper=new QueryWrapper<>();
        wrapper.eq("wid",wid);
        List<StudentWorkhome> list = sws.list(wrapper);
        List<String> paths = list.stream().map(
            (swh)->{
                return path+swh.getAttachment();
            }
        ).collect(Collectors.toList());
        if (paths.size() != 0) {
            // 创建临时路径,存放压缩文件
            String zipFilePath = path+wid+".zip";
            // 压缩输出流,包装流,将临时文件输出流包装成压缩流,将所有文件输出到这里,打成zip包
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
            // 循环调用压缩文件方法,将一个一个需要下载的文件打入压缩文件包
            for (String path : paths) {
                // 该方法在下面定义
                FileUtil.fileToZip(path, zipOut);
            }
            // 压缩完成后,关闭压缩流
            zipOut.close();
            response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(wid+".zip","utf-8"));
            //3.把文件放入到response里面。
            //下载完成之后，删掉这个zip包
            File fileTempZip = new File(zipFilePath);
            FileUtils.copyFile(fileTempZip,response.getOutputStream());
            fileTempZip.delete();
        }
    }
}

